import React from 'react';
import ReactDOM from 'react-dom';
import { actions, connect } from 'mirrorx';
import { ListView, List } from 'antd-mobile';


const Item = List.Item;
let data = [];
let pageIndex = 1;	 //当前页码
let pageSize = 10;  //每页显示数量
let pageTotal = 0; //总页数
let datas = [];  //用于存放合并的数据
function genData(pIndex = 0 ,data) { 
  for (let i = 0; i < data.length; i++) {   
     datas.push(data[i]);
  }
  return  datas;
}

class App extends React.Component {
  constructor(props) {
    super(props);
    const dataSource = new ListView.DataSource({
      rowHasChanged: (row1, row2) => row1 !== row2,
    });

    this.state = {
      dataSource,
      isLoading: true,
      hasMore: true
    };
  }

  componentDidMount() {

    // you can scroll to the specified position
    // setTimeout(() => this.lv.scrollTo(0, 120), 800);

    // simulate initial Ajax
        T.fetch({
          url: "/bill/payment/list.json",
          data: { pageIndex: 1, pageSize: pageSize },
        }).then((res) => {
          console.log(res);
          data = res.value.results;
          pageTotal = Math.ceil(res.value.total / pageSize);
          if (pageTotal == pageIndex) {
            this.setState({
              hasMore: false
            });
          }
          this.rData = data;
          datas = data;
          this.setState({
            dataSource: this.state.dataSource.cloneWithRows(this.rData),
            isLoading: false,
          });
        })
  }

billDetail=(billId) =>{//跳转到账单详情	
  console.log(billId)
		 actions.routing.push({
            pathname: 'bill-detail',
            search: '?renewalOrderNo=' + billId + "&renewalStatus=" + 2
            })
	}

  onEndReached = (event) => {
    // load new data
    // hasMore: from backend data, indicates whether it is the last page, here is false   
    if (this.state.isLoading && !this.state.hasMore) {      
      return;
    }
    console.log('reach end', event);
    this.setState({ isLoading: true });    
    T.fetch({
      url: "/bill/payment/list.json",
      data: { pageIndex: ++pageIndex, pageSize: pageSize },
    }).then((res) => {
      data = res.value.results;  
      datas = genData(pageIndex ,data);
      this.rData = { ...this.rData, ... datas};
      this.setState({
        dataSource: this.state.dataSource.cloneWithRows(this.rData),
        isLoading: false,
      });
      if (pageTotal == pageIndex) {
        this.setState({
          hasMore: false
        });
      }
    })
  }

  render() {
    const Lang = window.LangMessage ||{};
    const separator = (sectionID, rowID) => (
      <div
        key={`${sectionID}-${rowID}`}
        style={{
          backgroundColor: '#F5F5F9',
          height: 8,
          borderTop: '1px solid #ECECED',
          borderBottom: '1px solid #ECECED',
        }}
      />
    );
    let index = data.length - 1;
    const row = (rowData, sectionID, rowID) => {
      if (index < 0) {
        index = data.length - 1;
      }
      const obj = data[index--];
      return (
        <div key={obj.policyNo} style={{ padding: '0 15px' }}>
          <Item arrow="horizontal" onClick={() => this.billDetail(obj.renewalOrderNo)}>
            <div style={{ display: '-webkit-box', display: 'flex', padding: '15px 0' }} className="flex-between">
              <div><p>{obj.packageName}</p><p>{obj.policyNo}</p></div>
              <div><p>{obj.amt}元</p><p>{obj.dueDate}</p></div>
            </div>
          </Item>
        </div>
      );
    };
    return (
      <ListView
        ref={el => this.lv = el}
        dataSource={this.state.dataSource}
        renderFooter={() => (<div style={{ padding: 30, textAlign: 'center' }}>
          {this.state.isLoading ? Lang.load_more || '加载更多' : Lang.load_finish || '加载完成'}
        </div>)}
        renderRow={row}
        renderSeparator={separator}
        className="am-list"
        pageSize={10}
        useBodyScroll
        onScroll={() => { console.log('scroll'); }}
        scrollRenderAheadDistance={500}
        onEndReached={this.onEndReached}
        onEndReachedThreshold={10}  
      />
    );
  }
}

export default App;